<?php
namespace app\common\controller;
use think\Loader;
use think\Controller;
use think\Session;
use app\common\model\ActionLog;
use app\spadmin\library\Auth;
use think\Db;

class Backend extends Controller
{
    protected $model;
    protected $auth;

    use \app\spadmin\library\traits\backend;

    public function _initialize()
    {
        $adminhost =Db::name('Config')->where('name','adminHost')->value('value');
        if(!empty($adminhost)){
            $host = $this->request->host(true);
            if($host !== $adminhost){
                die('访问限制');
            }
        }
        $modulename = $this->request->module();
        $controllername = Loader::parseName($this->request->controller());
        $actionname = strtolower($this->request->action());
        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        $this->auth = Auth::instance();
        $this->auth->setRequestUri($path);
        $actionLog['module'] = $modulename;
        $actionLog['method'] = $this->request->method();
        $actionLog['ip'] = $this->request->ip();
        $actionLog['user_agent'] = $this->request->server('HTTP_USER_AGENT');
        $actionLog['action'] = $path;
        if($actionLog['action'] == 'login/index'){
            if($actionLog['method'] == 'post'){
                $actionLog['type'] = 2;
                $actionLog['username']=$this->request->post('username');
            }
        }else{
            $actionLog['type']=1;
            $actionLog['admin_id'] = $this->auth->id??'0';
        }
        $actionLog['param'] = $this->request->query()?json_encode($this->request->query(),1):'';
        ActionLog::create($actionLog,true);
        //不需要登录的url
        $noLoginUrl = $this->auth->getNologinRole();
        if(!in_array($path,$noLoginUrl)){
            //检测是否登录
            if (!$this->auth->isLogin()) {
                $url = Session::get('referer');
                if (in_array($this->request->pathinfo(), ['/', 'index/index'])) {
                    $this->redirect('index/login', [], 302, ['referer' => '']);
                    exit;
                }
                if($actionname == 'index'){
                    $url =  $this->request->url();
                    $this->redirect('index/login', [], 302, ['referer' => $url]);
                    exit();
                }
                $this->error('登录失效，请重新登陆',url('index/login'));
            }
            //不需要权限的url
            $noauthUrl = $this->auth->getNoAuthRole();
            if(!in_array($path,$noauthUrl)){
                // 判断控制器和方法是否有对应权限
                if (!$this->auth->check($path)) {
                    $this->error('无权访问', '');
                }
            }
        }else{
            if($path == 'index/login' && $this->auth->isLogin()){
                $url = Session::get('referer');
                $this->redirect('index/index', [], 200, ['referer' => $url]);
            }
        }
    }


}